package com.supcalls.service;
import com.supcalls.util.DatabaseLockUtil;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class OrderService {

    private final DatabaseLockUtil databaseLockUtil;

    public OrderService(DatabaseLockUtil databaseLockUtil) {
        this.databaseLockUtil = databaseLockUtil;
    }

    /**
     * 处理订单，防止并发
     */
    public void processOrder() {
        String lockKey = "order_lock";
        long timeoutMillis = 30000; // 锁定时间30秒

        // 尝试获取锁
        if (!databaseLockUtil.tryLockWithTimeout(lockKey, timeoutMillis)) {
            System.out.println("获取锁失败，已有其他线程在处理");
            return;
        }

        try {
            System.out.println("成功获取锁，开始处理订单...");
            TimeUnit.SECONDS.sleep(5); // 模拟业务逻辑
            System.out.println("订单处理完成！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            databaseLockUtil.releaseLockIfTimeout(lockKey); // 释放锁
            System.out.println("成功释放锁");
        }
    }
}

